//
//  SEGBigNavigationView.m
//  SEGBasicBussiness
//
//  Created by 揭婧雯 on 2018/12/17.
//  Copyright © 2018 刘山. All rights reserved.
//

#import "SEGBigNavigationView.h"

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

#import <Masonry/Masonry.h>

#if __has_include(<Commom/SEGColorManager.h>)
#import <Commom/SEGColorManager.h>
#else
#import "SEGColorManager.h"
#endif
#if __has_include(<Commom/UIControl+YYAdd.h>)
#import <Commom/UIControl+YYAdd.h>
#else
#import "UIControl+YYAdd.h"
#endif

#if __has_include(<Commom/UIControl+YYAdd.h>)
#import <Commom/UIControl+YYAdd.h>
#else
#import "UIControl+YYAdd.h"
#endif

#if __has_include(<Commom/UIImage+SEGTheme.h>)
#import <Commom/UIImage+SEGTheme.h>
#else
#import "UIImage+SEGTheme.h"
#endif

#if __has_include(<SEGPlatform/SEGPlatformManager.h>)
#import <SEGPlatform/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

@interface SEGBigNavigationView ()
/**
 标题
 */
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *titleButton;
@property (nonatomic, strong) UIImageView *titleImageView;
@property (nonatomic, strong) UIImageView *arrowImage;
/// 按钮array
@property (nonatomic, strong) NSArray *buttonArr;
@property (nonatomic, copy) void(^tapBlock)(void);
/// 返回按钮
@property (nonatomic, strong) UIButton *backBtn;

@end

@implementation SEGBigNavigationView

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    return [self initWithType:SEGBigNavBar_normal];
}
- (instancetype)init {
    return [self initWithType:SEGBigNavBar_normal];
}
- (instancetype)initWithFrame:(CGRect)frame {
    return [self initWithType:SEGBigNavBar_normal];
}
- (instancetype)initWithType:(SEGBigNavBarType)type {
    if (self = [super initWithFrame:CGRectZero]) {
        [self setUpUIWithType:type];
    }
    return self;
}

- (void)setUpUIWithType:(SEGBigNavBarType)type {
    if (type == SEGBigNavBar_normal) {
        self.frame = CGRectMake(0, 0, LYScreenWidth(), KBigNavHeight);
    } else {
        self.frame = CGRectMake(0, 0, LYScreenWidth(), kBackBtn_BigNavHeight);
    }
    self.backgroundColor = kColor_W;
    
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = self.backgroundColor;
    label.layer.masksToBounds = YES;
    label.font = [UIFont boldSystemFontOfSize:25];
    label.textColor = kColor_1;
    [self addSubview:label];
    self.titleLabel = label;
    
    if (type == SEGBigNavBar_normal) {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).mas_offset(15);
            make.top.equalTo(self).mas_offset(kStatusbarHeight);
            make.height.mas_equalTo(KBigNavTitleLabelHeight);
            make.width.mas_lessThanOrEqualTo(LYScreenWidth()-30-10);
        }];
    } else { // 带返回按钮
        UIImage *backImage = [UIImage imageWithContentsOfFile:SEGPicName(@"back")];
        self.backBtn = ({
            UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [backBtn setImage:backImage forState:UIControlStateNormal];
            [backBtn setBackgroundColor:kColor_W];
            [backBtn addTarget:self
                        action:@selector(gotoBack)
              forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:backBtn];
            backBtn;
        });
        
        [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).mas_offset(15);
            make.top.equalTo(self).mas_offset(kStatusbarHeight);
            make.width.mas_equalTo(backImage.size.width);
            make.height.mas_equalTo(backImage.size.height);
        }];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).mas_offset(30);
            make.top.equalTo(self).offset(kStatusbarHeight+44);
            make.height.mas_equalTo(kBackBtn_BigNavHeight-(kStatusbarHeight+44));
        }];
    }
    
    self.arrowImage = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.backgroundColor = kColor_W;
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"icon_qiehuanxiaoqu")];
        imageView.image = [imageView.image imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
        imageView.tintColor = kColor_1;
        [self addSubview:imageView];
        imageView;
    });
    [self.arrowImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_right).offset(6);
        make.centerY.equalTo(label);
    }];
    self.arrowImage.hidden = YES;
    
    self.titleImageView = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        [self addSubview:imageView];
        imageView;
    });
    [self.titleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.centerY.equalTo(label);
    }];
    self.titleImageView.hidden = YES;
}

#pragma mark - 设置标题
- (void)setTitleWithString:(NSString *)string {
    self.titleLabel.text = string;
}
// 设置标题图片
- (void)setTitleWithImage:(UIImage *)image {
    self.titleImageView.hidden = NO;
    self.titleImageView.image = image;
}

- (void)addTitleTapBlock:(void(^)(void))block {
    self.tapBlock = block;
    if (!self.titleButton) {
        self.titleButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button addTarget:self action:@selector(seg_titleButtonTap:) forControlEvents:UIControlEventTouchUpInside];
            button.backgroundColor = UIColor.clearColor;
            [self addSubview:button];
            button;
        });
        
        [self.titleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(self.titleLabel);
            if (self.arrowImage.isHidden) {
                make.right.equalTo(self.titleLabel);
            } else {
                make.right.equalTo(self.arrowImage).offset(15);
            }
        }];
    }
}

- (void)showArrowImage {
    self.arrowImage.hidden = NO;
    
    [self.titleButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.titleLabel);
        if (self.arrowImage.isHidden) {
            make.right.equalTo(self.titleLabel);
        } else {
            make.right.equalTo(self.arrowImage).offset(15);
        }
    }];
}

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // 更新导航按钮图片模式
    if (self.backBtn.currentImage) {
        [self.backBtn setImage:[UIImage imageWithContentsOfFile:self.backBtn.currentImage.anyNamePath] forState:UIControlStateNormal];
    }
    if (self.rightButton.currentImage) {
        [self.rightButton setImage:[UIImage imageWithContentsOfFile:self.rightButton.currentImage.anyNamePath] forState:UIControlStateNormal];
    }
    if (self.buttonArr.count > 0) {
        [self.buttonArr enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL * _Nonnull stop) {
            UIImage *image = button.currentImage;
            [button setImage:[UIImage imageWithContentsOfFile:image.anyNamePath] forState:UIControlStateNormal];
        }];
    }
}

#pragma mark - 设置按钮
// 添加右侧按钮
- (void)addRightButtonWithImage:(UIImage *)image tapBlock:(void(^)(void))block {
    [self addRightButtonWithImage:image title:nil tapBlock:block];
}
- (void)addRightButtonWithTitle:(NSString *)title tapBlock:(void(^)(void))block {
    [self addRightButtonWithImage:nil title:title tapBlock:block];
}
- (void)addRightButtonWithImage:(UIImage *)image title:(NSString *)title tapBlock:(void (^)(void))block {
    if (self.rightButton.superview) [self.rightButton removeFromSuperview];
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.backgroundColor = kColor_W;
    [self.rightButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        //点击后消除红点
        UIView *reddot = [sender viewWithTag:5555];
        reddot.hidden = YES;
        if (block) block();
    }];
    [self addSubview:self.rightButton];
    
    // 红点 默认隐藏
    UIImageView *redImageView = [[UIImageView alloc] init];
    redImageView = [[UIImageView alloc] init];
    redImageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"tab_red_round")];
    redImageView.contentMode = UIViewContentModeScaleAspectFill;
    redImageView.tag = 5555;
    [self.rightButton addSubview:redImageView];
    [redImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rightButton).mas_offset(1);
        make.right.equalTo(self.rightButton).mas_offset(0);
        make.width.height.mas_equalTo(8);
    }];
    redImageView.hidden = YES;

    if (image && !title) { // 只有图片
        [self.rightButton setImage:image forState:UIControlStateNormal];
        [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleLabel);
            make.right.equalTo(self).offset(-10.0);
            make.width.mas_equalTo(image.size.width + 10);
            make.height.mas_equalTo(image.size.height + 10);
        }];
    } else if (!image && title) { // 只有文字
        self.rightButton.titleLabel.font = kFont_15;
        [self.rightButton setTitleColor:kColor_1 forState:UIControlStateNormal];
        [self.rightButton setTitle:title forState:UIControlStateNormal];
        [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleLabel);
            make.right.equalTo(self).offset(-15);
            make.width.mas_lessThanOrEqualTo(LYScreenWidth()-160);
            make.height.mas_equalTo(45);
        }];
        // 修改红点坐标
        [redImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.rightButton).mas_offset(4);
        }];
        
    } else if (image && title) { // 图片+文字
        self.rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:15.f];
        self.rightButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [self.rightButton setTitleColor:kColor_1 forState:UIControlStateNormal];
        [self.rightButton setTitle:title forState:UIControlStateNormal];
        [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleLabel);
            make.right.equalTo(self).offset(-15);
            make.width.mas_lessThanOrEqualTo(LYScreenWidth()-160);
            make.height.mas_equalTo(45);
        }];
        for (UIImageView *img in self.subviews) {
            if (img.tag == 10086) [img removeFromSuperview];
        }
        UIImageView *leftImageView = [[UIImageView alloc] init];
        leftImageView.tag = 10086;
        leftImageView.image = image;
        [self addSubview:leftImageView];
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.rightButton.mas_left).offset(-5);
            make.centerY.equalTo(self.titleLabel);
            make.width.mas_equalTo(image.size.width);
            make.height.mas_equalTo(image.size.height);
        }];
        // 修改红点坐标
        [redImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.rightButton).mas_offset(4);
        }];
    }
}
- (void)updateRightButtonRedDot:(BOOL)isRedDot {
    UIView *reddot = [self.rightButton viewWithTag:5555];
    reddot.hidden = !isRedDot;
}
- (void)addRightButtonsWithButtonArray:(NSArray *)buttonArray {
    if (buttonArray.count == 0) return;
    self.buttonArr = buttonArray;
    UIButton *lastButton;
    
    CGFloat rightPadding = 22.0 - addPadding; // 按钮右边间距
    CGFloat buttonXPadding = 30.0 - addPadding * 2; // 按钮水平间距
    for (NSInteger i = self.buttonArr.count - 1 ; i >= 0  ; i--) {
        UIButton *button = self.buttonArr[i];
        UIImage *image = button.currentImage;
        [self addSubview:button];
        if (i == self.buttonArr.count - 1) { // 最右边的按钮
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.titleLabel).offset(-18 + addPadding);
                make.right.equalTo(self).offset(-rightPadding);
                make.width.mas_equalTo(image.size.width + addPadding * 2);
                make.height.mas_equalTo(image.size.height + addPadding * 2);
            }];
        }else {
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(lastButton);
                make.right.equalTo(lastButton.mas_left).offset(-buttonXPadding);
                make.width.mas_equalTo(image.size.width + addPadding * 2);
                make.height.mas_equalTo(image.size.height + addPadding * 2);
            }];
        }
        lastButton = button;
    }
}

#pragma mark - 私有方法
- (void)seg_titleButtonTap:(UIButton *)sender {
    if (self.tapBlock) self.tapBlock();
}
#pragma mark - 返回按钮Event
- (void)gotoBack {
    UIViewController *currentVC = [self seg_currentViewController];
    [currentVC.navigationController popViewControllerAnimated:YES];
}
- (UIViewController *)seg_currentViewController {
    UIViewController *resultVC;
    resultVC = [self seg_topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self seg_topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
- (UIViewController *)seg_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self seg_topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self seg_topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

#pragma mark - Setter
-(void)setLeftMargin:(CGFloat)leftMargin {
    if (leftMargin == _leftMargin) return;
    [_titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).mas_offset(leftMargin);
    }];
}
- (void)setFontSize:(CGFloat)fontSize {
    if (fontSize == _fontSize) return;
    _titleLabel.font = [UIFont boldSystemFontOfSize:fontSize];
}

@end
